package cn.hyy.hrm.controller;

import cn.hyy.basic.util.AjaxResult;
import cn.hyy.basic.util.PageList;
import cn.hyy.hrm.doc.CourseDoucment;
import cn.hyy.hrm.doc.query.CourseDocumentQuery;
import cn.hyy.hrm.repository.CourseRepository;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/course")
public class CourseESController {
    @Autowired
    private CourseRepository repository;

    /**
     * 添加文档数据
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody CourseDoucment courseDoucment){
        try {
            repository.save(courseDoucment);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败"+e.getMessage());
        }
    }
    /**
     * 批量添加文档
     */
    @PostMapping("/saveBathc")
    public AjaxResult saveBathc(@RequestBody List<CourseDoucment> courseDoucments){
        try {
            repository.saveAll(courseDoucments);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("失败"+e.getMessage());
        }
    }
    /**
     * 删除文档数据
     */
    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("id") Long id){
        try {
            repository.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除文档失败！"+e.getMessage());
        }
    }
    /**
     * 批量删除文档数据
     */
    @DeleteMapping("/deleteBatch")
    public AjaxResult delete(@RequestBody List<Long> ids){
        try {
            for (Long id : ids) {
                repository.deleteById(id);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除文档失败！"+e.getMessage());
        }

    }
    /**
     * 检索文档数据
     * @return
     */
    @PostMapping("/search")
    public PageList<CourseDoucment> search(@RequestBody CourseDocumentQuery query){

        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        //构建查询条件
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        //关键字
        if(!StringUtils.isEmpty(query.getKeyword())){
            boolQueryBuilder.must(new MatchQueryBuilder("all",query.getKeyword()));
        }
        //过滤
        List<QueryBuilder> filter = boolQueryBuilder.filter();
        //课程类型
        if(query.getProductTypeId()!=null){
            filter.add(new TermQueryBuilder("typeId",query.getProductTypeId()));
        }
        //收费规则
        if(query.getCharge()!=null){
            filter.add(new TermQueryBuilder("charge",query.getCharge()));
        }
        //等级
        if(query.getGrade()!=null){
            filter.add(new TermQueryBuilder("grade",query.getGrade()));
        }

        //价格，在最大价格和最小价格之间
        if(query.getMinPrice()!=null){
            filter.add(new RangeQueryBuilder("price").gte(query.getMinPrice()));
        }
        if(query.getMaxPrice()!=null){
            filter.add(new RangeQueryBuilder("price").lte(query.getMinPrice()));
        }
        builder.withQuery(boolQueryBuilder);


        //排序 - 排序字段
        String sortField = query.getSortField();
        if(StringUtils.isEmpty(sortField)){
            //默认以“新品来排序”
            sortField = "startTime";
        }
        //排序 - 排序方式
        String sortType = query.getSortType();
        SortOrder sortOrder = SortOrder.ASC;
        if("desc".equals(sortType)){
            sortOrder = SortOrder.DESC;
        }
        builder.withSort(new FieldSortBuilder(sortField).order(sortOrder));

        //分页
        builder.withPageable(PageRequest.of(query.getPage()-1,query.getRows()));

        //执行查询，将查询结果封装到PageList中
        Page<CourseDoucment> page = repository.search(builder.build());
        PageList<CourseDoucment> pageList = new PageList<>();
        pageList.setTotal(page.getTotalElements());
        pageList.setRows(page.getContent());

        return pageList;
    }
}
